package com.cloud.wechat;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.cloud.entity.AuthBody;
import com.cloud.entity.AuthUser;
import com.cloud.utils.StringUtils;
import org.apache.commons.lang3.ObjectUtils;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信工具类
 *
 * @author yzj
 */
public class WechatUtils {

    // 微信appid
    private String appid;

    // 微信密钥
    private String secret;

    public WechatUtils(String appid, String secret) {
        this.appid = appid;
        this.secret = secret;
    }

    /**
     * 获取微信授权码
     *
     * @param callBack 回调地址
     */
    public void getWechatCode(String callBack) {
        try {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("appid", appid);
            paramMap.put("redirect_uri", URLEncoder.encode("", "utf-8"));
            paramMap.put("response_type", "code");
            paramMap.put("scope", "snsapi_base");
            paramMap.put("state", "TATE#wechat_redirect");
            HttpUtil.get("https://open.weixin.qq.com/connect/oauth2/authorize", paramMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取微信用户信息
     *
     * @param code 授权码
     */
    public AuthUser getWechatUserInfo(String code) {
        AuthUser authUser = null;
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid", appid);
        paramMap.put("secret", secret);
        paramMap.put("code", code);
        paramMap.put("grant_type", "authorization_code");
        String result = HttpUtil.get("https://api.weixin.qq.com/sns/oauth2/access_token", paramMap);
        JSONObject apiResult = JSONObject.parseObject(result);
        if (StringUtils.isNotBlank(apiResult.getString("errcode"))) {
            return null;
        }
        String openId = apiResult.getString("openid");
        String accessToken = apiResult.getString("access_token");
        if (StringUtils.isNotBlank(openId) || StringUtils.isNotBlank(accessToken)) {
            // 获取微信用户信息
            Map<String, Object> paramMap2 = new HashMap<>();
            paramMap2.put("access_token", accessToken);
            paramMap2.put("openid", openId);
            String result2 = HttpUtil.get("https://api.weixin.qq.com/sns/userinfo", paramMap2);
            JSONObject apiResult2 = JSONObject.parseObject(result2);
            if (apiResult2.getString("errcode").equals("0")) {
                authUser = new AuthUser();
                authUser.setOpenid(apiResult2.getString("openid"));
                authUser.setNickNameCn(apiResult2.getString("nickname"));
                authUser.setGovEmpAvatar(apiResult2.getString("headimgurl"));
                authUser.setMobile(apiResult2.getString("mobile"));
            }
        }
        return authUser;
    }

    /**
     * 获取微信小程序用户信息
     *
     * @param authBody 请求认证信息
     * @return
     */
    public AuthUser getMinAppUserInfo(AuthBody authBody) {
        AuthUser authUser = null;
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid", appid);
        paramMap.put("secret", secret);
        paramMap.put("js_code", authBody.getAuthCode());
        paramMap.put("grant_type", "authorization_code");
        String result = HttpUtil.get("https://api.weixin.qq.com/sns/jscode2session", paramMap);
        JSONObject apiResult = JSONObject.parseObject(result);
        if (ObjectUtils.isNotEmpty(apiResult)) {
            String openId = apiResult.getString("openid");
            String sessionKey = apiResult.getString("session_key");
            // 解密用户信息
            if (StringUtils.isNotEmpty(openId) || StringUtils.isNotEmpty(sessionKey)) {
                String resData = AesCbcUtils.decrypt(authBody.getEncryptData(), sessionKey, authBody.getAuthCode());
                authUser = new AuthUser();
                JSONObject userJson = JSONObject.parseObject(resData);
                authUser.setOpenid(openId);
                authUser.setAccountId(userJson.get("unionId").toString());
                authUser.setNickNameCn(userJson.get("nickname").toString());
                authUser.setEmpGender(userJson.get("gender").toString());
                authUser.setGovEmpAvatar(userJson.get("avatarUrl").toString());
                return authUser;
            }
        }
        return authUser;
    }

}
